<!--
mc-query-url:初始化表格的后台接口
mc-query-method： post get
:before-submit-form: 是一个事件方法 但是不要@  当返回true时，继续提交，否则不提交
mc-save-url:表单提交地址
mc-delete-url:
废弃
-->
<template>
    <div class="mc-vxe-table">
        <el-row>
          <el-col :span="24"  ref="queryRef">
              <!-- 这个slot位置别换 不然遍历算法找不到-->
              <slot name="query" :query="queryData"></slot>
              <el-button @click="queryTable" size="medium">查询</el-button>
              <el-button @click="resetQueryData" size="medium">重置</el-button>
              <el-button @click="insertData" size="medium" type="primary">新增</el-button>
          </el-col>
          <el-col :span="24">
              <vxe-table :data="tableData" v-bind="$attrs" v-on="$listeners" @cell-dblclick="dblClickCell">
                  <slot></slot>
                  <vxe-table-column title="操作" width="200" show-overflow>
                      <template #default="{ row,rowIndex }">
                        <slot name="operate" :row="row"></slot>
                        <el-button type="text" icon="fa fa-edit" @click="editEvent(row)">编辑</el-button>
                        <el-button type="text" icon="fa fa-trash-o" @click="removeEvent(row,rowIndex)">删除</el-button>
                      </template>
                  </vxe-table-column>
              </vxe-table>
          </el-col>
          <el-col :span="24">
              <el-pagination layout="prev,pager,next" :total="pageTotal" :page-size="pageSize" :current-page.sync="currentPage" @current-change="pageChange"
               :pager-count="pageCount"></el-pagination>
          </el-col>
          <el-col :span="24" class="mc-vxe-table-dialog">
              <el-dialog :show-close="false"
                :title="submitFormTitle"
                :visible.sync="dialogVisible"
                width="70%">
                     <!-- 抛出form变量给父亲组件 -->
                     <slot name="form" :form="formData"></slot>
                     <span slot="footer" class="dialog-footer">
                         <el-button @click="closeDialog">取消</el-button>
                         <el-button type="primary" @click="submitForm">确定</el-button>
                     </span>
              </el-dialog>
          </el-col>
          <el-col :span="24">
             <slot name="parent" :parent="parentRowData"></slot>
          </el-col>
        </el-row>

    </div>
</template>

<script>
var this_=null;
export default {
    name: 'mc-vxe-table',
    data () {
        return {
            pageCount:this.mcPagerCount,//大于=5小于=21的奇数
            pageSize:this.mcPageSize,
            pageTotal:100,
            currentPage:1,
            tableData: [],
            dialogVisible:false,
            formData:{},
            formDataSnapshot:{},//用于还原数据使用
            queryData:{},
            queryCondition : {},//查询条件比较符
            submitFormTitle:"",
            //孩子表需要的当前父亲这一行的数据
            parentRowData:{},
        }
    },
    props:
      {
        //页码数量
        'mcPagerCount':{type:Number,default:5},
        /*每页多少条*/
        'mcPageSize':{type:Number,default:10},
        /*请求数据*/
        'mcQueryUrl':{type:String},
        /*请求方法*/
        'mcQueryMethod':{type:String},
        /*表单提交*/
        'mcSaveUrl':{type:String},
        /*当提交表单存储数据前调用*/
        'beforeSubmitForm':{type:Function,default:null},
        /*删除一条记录地址*/
        'mcDeleteUrl':{type:String},
        //下面的功能父子表可用
        /*固定额外查询条件*/
        'mcFromParentQuery':{type:Object,default:null},
        /*外键父亲字段名 如果多个就逗号分隔  {'pid':'id'} 子表外键名:父亲键名 */
        'mcPidFieldMap':{type:Object,default:null}
      },
      watch:{
          mcFromParentQuery:{
            handler(newValue){
                //触发请求表格数据
                this.queryTable();
            },
            deep:true
          }
      },
    methods:{
        afterQuery:function(data,successMsg){
            if(data){
                if(typeof data['code']!== 'undefined' && data.code===0){
                    if(successMsg){
                        this.$message({message:successMsg,type:"success"});
                        return true;
                    }
                }else{
                    if(data['msg']){
                        this.$message.error(data.msg);
                        return false;
                    }
                }
            }
            return true;
        },
        editEvent:function(row){
            this.submitFormTitle = "编辑";
            this.formData = row;
            this.formDataSnapshot = JSON.parse(JSON.stringify(row));
            setTimeout(()=>{
                this.dialogVisible = true;
            },300)
        },
        /*新增*/
        insertData:function(){
            this.submitFormTitle = "新增";
            var defaultMap = {}
            this.formData = {};
            this.formDataSnapshot = JSON.parse(JSON.stringify(defaultMap));
            this.dialogVisible = true;
        },
        removeEvent:function(row,rowIndex){
            var request = this.$magicaltool.request;
            var _t = this;
            if(!this.mcDeleteUrl){
                this.$message.error("请配置删除地址");
                return;
            }
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                      confirmButtonText: '确定',
                      cancelButtonText: '取消',
                      type: 'warning'
                    }).then(() => {
                       request.axios({$vue:this,method:"post",url:this.mcDeleteUrl,data:row,
                                       headers:{'content-type':'application/json;charset=UTF-8'}}).then(function(res) {
                                            if(_t.afterQuery(res)){
                                               _t.tableData.splice(rowIndex,1);
                                            }
                                   }).catch(function (error) {
                                       console.log(error)
                                   });
                    }).catch(() => {

                    });
        },
        closeDialog:function(){
            for(var key in this.formDataSnapshot){
                this.formData[key] = this.formDataSnapshot[key];
            }
            this.dialogVisible = false;
        },
        //表单提交
        submitForm:function(){
            var request = this.$magicaltool.request;
            if(!this.mcSaveUrl){
                this.$message.error("请配置表单提交地址");
                return;
            }
            if(this.beforeSubmitForm){//之所以不用$emit是因为我要返回数据 判断是否继续往下提交
                if(!this.beforeSubmitForm(this.formData)){
                    return;
                }
            }

            var saveData = {};
            for(var key in this.formData){
                if(this.formData[key]!== null){
                    saveData[key] = this.formData[key];
                }
            }
            var _t = this;
            request.axios({$vue:this,method:"post",url:this.mcSaveUrl,data:saveData,
                headers:{'content-type':'application/json;charset=UTF-8'}}).then(function(res) {
                     _t.afterQuery(res,"操作成功");
                     _t.dialogVisible = false;
                     if(_t.submitFormTitle=='新增'){//刷新下表格
                        _t.queryTable();
                     }
            }).catch(function (error) {
                console.log(error)
            });

        },
        buildMcDataUrl:function(){
            if(this.mcQueryUrl){
                var newArr = [];
                var arr = this.mcQueryUrl.split("?");
                newArr.push(arr[0]);
                if(arr.length<=1){
                    return this.mcQueryUrl+"?page="+this.currentPage+"&limit="+this.pageSize;
                }
                var paramMap = [];
                var arr2 = arr[1].split("&");
                var findPage = false,findLimit=false;
                for(var i=0;i<arr2.length;i++){
                    var arr3 = arr2[i].split("=");
                    if(arr3[0]=='page'){
                        findPage = true;
                        paramMap.push("page="+this.currentPage);
                    }else if(arr3[0]=='limit'){
                        findLimit = true;
                        paramMap.push("limit="+this.pageSize);
                    }else{
                        paramMap.push(arr2[i]);
                    }
                }
                if(!findPage){
                    paramMap.push("page="+this.currentPage);
                }
                if(!findLimit){
                    paramMap.push("limit="+this.pageSize);
                }
                newArr.push(paramMap.join("&"))
                return  newArr.join("?");
            }
            return "";
        },
        buildQueryData:function(data){
            var newData = {};
            if(data){
                for(var key in data){
                    var value = data[key];
                    if(value !== null && value !== "" && typeof value != 'undefined' ){//忽略这些查询条件入参
                        newData[key] = value;
                    }
                }
            }
            if(this.mcFromParentQuery){
                if(this.mcPidFieldMap){
                    for(var childName in this.mcPidFieldMap){
                      var parentName = this.mcPidFieldMap[childName]
                      var value = this.mcFromParentQuery[parentName];
                      if(value !== null && value !== "" && typeof value != 'undefined'){
                          newData[childName] = value;
                      }
                    }
                }
            }
            return newData;
        },
        //查询功能
        queryTable:function(){
            var request = this.$magicaltool.request;
            var _t=this;
            if(this.mcQueryUrl){
                var queryData = this.buildQueryData(this.queryData);
                if(this.mcQueryMethod=='post'){
                    request.axios({$vue:this,method:"post",url:this.buildMcDataUrl(),data:{param:queryData,condition:this.queryCondition},
                        headers:{'content-type':'application/json;charset=UTF-8'}}).then(function(res) {
                             _t.afterQuery(res);
                             _t.pageTotal = res.count;
                             _t.tableData=res.data;
                    }).catch(function (error) {
                        console.log(error)
                    });
                }else{
                     request.axios({$vue:this,method:"get",url:this.buildMcDataUrl(),params:{param:queryData,condition:this.queryCondition }}).then(function(res) {
                              _t.afterQuery(res);
                              _t.pageTotal = res.count;
                              _t.tableData=res.data;
                     }).catch(function (error) {
                         console.log(error)
                     });
                }
            }
        },

        /*页面点击*/
        pageChange:function(page){
            this.queryTable();
        },
        resetQueryData:function(){
            this.queryData = {}
        },
        findQueryCondition:function(){
            var queryRef = this.$refs['queryRef'];
            var querySlot = queryRef.$slots.default[0];
            var conditionMap = {};
            if(querySlot.componentInstance){
                this.iteratorChildren(querySlot.componentInstance,conditionMap);
            }
            return conditionMap;
        },
        //递归算法 查找查询条件
        iteratorChildren:function(component,valueMap){
            if(component){
                var mcCondition = component.$attrs['mc-condition'];
                if(mcCondition){
                    var vnode =  component._self.$vnode;
                    var data = vnode.data;
                    if(data['model']){//v-model藏得太深了 注意上传文件这里没搞 TODO
                      var expression = data.model.expression;
                      if(expression.indexOf(".")!=-1){
                          var arr = expression.split(".");
                          valueMap[arr[arr.length-1]] = mcCondition;
                      }
                    }
                }

                var children = component.$children;
                if(children&& children.length>0){
                    for(var i=0;i<children.length;i++){
                        this.iteratorChildren(children[i],valueMap);
                    }
                }
            }
        },
        dblClickCell(cellData,e){
            var rowIndex = cellData.rowIndex;
            this.parentRowData = cellData.data[rowIndex];

        }
    },
    mounted () {
        var _this = this;
        setTimeout(function(){//slot内加载速度比较慢，等待一会
            _this.queryCondition = _this.findQueryCondition();//遍历查询条件
            _this.resetQueryData();
            _this.queryTable();
            console.log(_this.formData)
        },500)
    },

}

</script>

<style lang="scss">
    .mc-vxe-table-dialog{
        .el-dialog {
            height: 80%;
            .el-dialog__body {
                height : 70%;
                overflow-y: auto;
                .mc-ui-absolute-pane{
                    position: relative;
                    height : 100%;
                }
            }
            .el-dialog__footer{
                position: absolute;
                right:0;
                bottom:0;
            }

        }
    }
    .mc-vxe-table>.el-row>.el-col{
      margin-top:10px;
    }

</style>
